#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("服务器");
    //创建QTcpServer实例
    tcpServer=new QTcpServer(this);
    //指定信号槽处理连接
    connect(tcpServer,&QTcpServer::newConnection,this,&MainWindow::handelConnect);
    //绑定监听
    if(tcpServer->listen(QHostAddress::Any,9090)==false)
    {
        QMessageBox::critical(this,"服务器启动失败",tcpServer->errorString());
        exit(-1);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::handelConnect()
{
    //拿到socket对象
    QTcpSocket* clientSocket=tcpServer->nextPendingConnection();
    QString log="["+clientSocket->peerAddress().toString()+":"+
          QString::number(clientSocket->peerPort())+"] 客户端上线!";
    ui->listWidget->addItem(log);


    //通过信号槽处理客户端请求
    connect(clientSocket,&QTcpSocket::readyRead,this,[=](){
        //读取请求数据
        QString requset=clientSocket->readAll();
        //处理请求服务器
        const QString& response=handel(requset);
        //回显到客户端
        clientSocket->write(response.toUtf8());
        //上述记录记录到日志中
        QString log="["+clientSocket->peerAddress().toString()+":"+
                QString::number(clientSocket->peerPort())+"]"+"req:"+
                requset+"req:"+response;
        ui->listWidget->addItem(log);
    });


    //通过信号槽处理客户端断开连接
    connect(clientSocket,&QTcpSocket::disconnected,this,[&clientSocket,this](){
        //记录日志
        QString log="["+clientSocket->peerAddress().toString()+":"+
              QString::number(clientSocket->peerPort())+"] 客户端断开连接!";
        ui->listWidget->addItem(log);
        //稍后释放连接
        clientSocket->deleteLater();

    });
}

QString MainWindow::handel(const QString &request)
{
    //回显服务器
    return request;
}

